package icu.sehnen.controller;


import com.alibaba.fastjson.JSONObject;
import icu.sehnen.common.CommonResult;
import icu.sehnen.common.ResultCode;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.UUID;

//@Controller
@RestController
public class UploadController {

	// 先发出一个get请求,显示一个上传页面
	// localhost/upload get提交
//	@RequestMapping(value= "upload", method = RequestMethod.GET)
//	@GetMapping("/upload")
//	public String get() throws Exception {
//		return "upload";
//	}

	// <form action="upload" method="post" enctype="multipart/form-data">
	// 其他属性<input type="text" name="name"><br />
	// 文件属性<input type="file" name="upload"><br />
	// <input type="submit"/>
	// </form>

	// 上面页面一提交，就返回下面post方法

	// 发出一个post请求,处理文件的上传
	// localhost/upload post提交
	@CrossOrigin
	@PostMapping(value= "/upload")
	@ResponseBody
	public  CommonResult upload(@RequestParam("file") MultipartFile[] file, HttpSession session) throws Exception {
//	public String post(@RequestParam("file") MultipartFile[] file, String name, HttpServletRequest request) throws Exception {
//		System.out.println("其他属性name::" + name);
//		System.out.println("上传文件的类型:" + upload.getContentType());
//		System.out.println("上传文件名称:" + upload.getName());
//		System.out.println("上传文件文件名:" + upload.getOriginalFilename());
//		for (int i = 0; i < file.length; i++) {
//			MultipartFile multipartFile = file[i];
//			String uploadFilePath = uploadFile("/upload", multipartFile, session);
//			//输出返回结果
//			System.out.println(uploadFilePath );
//		}
		ArrayList<String> urlList = new ArrayList<>();
		for (int i = 0; i < file.length; i++) {
			MultipartFile multipartFile = file[i];
			String uploadFilePath = uploadFile("/upload", multipartFile, session);
			//输出返回结果
			urlList.add(uploadFilePath);
		}
		return   CommonResult.success(urlList,"文件上传成功");

//

	}

	private String uploadFile(String webPath, MultipartFile file, HttpSession session) {



//		String fileName = UUID.randomUUID().toString().replace("-", "").substring(0, 15) + "_file_" + file.getOriginalFilename();
//		// 文件后缀名
//		String ext = FilenameUtils.getExtension(upload.getOriginalFilename());'

//		System.out.println("filename"+fileName);
		try {
//			File file1 = new File(realPath);
//			if (!file1.exists()) {
//				//目录不在创造目录
//				file1.mkdirs();
//			}
//			移动文件到realpath下面
//			file.transferTo(new File(realPath + "/" + fileName));
//			//返回图片在服务器下的路径
//			return webPath + "/" + fileName;

			// 上传的流
			InputStream inputStream = file.getInputStream();
			// 获取webapp路径
			ServletContext context = session.getServletContext();
			//获得真实路径 realpath=C:\\Users\\Master\\Desktop\\ssm-integration-demo\\target\\artifacts\\sehnen_maven_v2_war_exploded\\upload
			// webPath ="/upload"
			String realPath = context.getRealPath(webPath);
			// 文件后缀名
			String ext = FilenameUtils.getExtension(file.getOriginalFilename());
			// 32位随机字符串
			String uuidStr = UUID.randomUUID().toString().replace("-", "");
			File file2 = new File(realPath, uuidStr + "." + ext);
			File parentFile = file2.getParentFile();
			if (!parentFile.exists()) {
				// 如果upload文件夹不存在，就创建
				parentFile.mkdirs();
			}
			// 拷贝到webapp一个目录里面
			IOUtils.copy(inputStream, new FileOutputStream(file2));

		    String prefix= realPath.split("target")[0];
//		    拷贝到真实的webapp目录下面
		        File outpath=new File(prefix+"/src/main/webapp/upload");
		        if(!outpath.exists()){
		            outpath.mkdirs();
                }

            File file1 = new File(outpath, uuidStr + "." + ext);
            IOUtils.copy(inputStream,new FileOutputStream(file1));
            return "/upload/" + uuidStr + "." + ext;
		} catch (IOException e) {

			e.printStackTrace();
			return null;
		}
	}











}